package kr.couponplay.android.activity.deal.list;

import java.util.List;

import kr.couponplay.android.activity.R;
import kr.couponplay.android.domain.BeanFactory;
import kr.couponplay.android.domain.deal.Deal;
import kr.couponplay.android.support.DisplayUtils;
import kr.couponplay.android.support.cache.ImageLoader;
import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class DealListViewAdapter extends ArrayAdapter<Deal> {
	private Context mContext;
	private int mResource;
	private List<Deal> deals;
	public ImageLoader imageLoader;
	private LayoutInflater mInflater;

	public DealListViewAdapter(Context context, int layoutResource, List<Deal> deals) {
		super(context, layoutResource, deals);
		this.mContext = context;
		this.mResource = layoutResource;
		this.deals = deals;
		imageLoader = BeanFactory.getBean(mContext.getApplicationContext(), ImageLoader.class);
		this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Deal deal = deals.get(position);

		if (convertView == null) {
			convertView = mInflater.inflate(mResource, parent, false);
		}

		if (deal != null) {
			ImageView imageView = (ImageView)convertView.findViewById(R.id.deal_thumbnail);
			TextView title = (TextView) convertView.findViewById(R.id.deal_title);
			TextView originalPrice = (TextView) convertView.findViewById(R.id.original_price);
			TextView salesPrice = (TextView) convertView.findViewById(R.id.sales_price);
			TextView discountRate = (TextView) convertView.findViewById(R.id.discount_rate);
			TextView nowCount = (TextView) convertView.findViewById(R.id.now_count);
			TextView saleEndAt = (TextView) convertView.findViewById(R.id.sale_end_date);
			TextView providerName = (TextView) convertView.findViewById(R.id.provider_name);

			imageLoader.displayImage(deal.getThumbnailImageUrl1(), imageView);
			title.setText(deal.display1());
			originalPrice.setText(DisplayUtils.numFormat(deal.getOriginalPrice()) + "원");
			originalPrice.setPaintFlags(originalPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
			salesPrice.setText(DisplayUtils.numFormat(deal.getSalesPrice()) + "원");
			discountRate.setText(deal.getDiscountRate() + "%");
			nowCount.setText(DisplayUtils.numFormat(deal.getNowCount()) + "개");
			saleEndAt.setText(DisplayUtils.dateFormat(Long.parseLong(deal.getToDate())) + "까지");
			providerName.setText(deal.getProvider().getName());
		}
		return convertView;
	}
	
	public Deal getItem(int position) {
		return deals.get(position);
	}
	
	public long getItemId(int position) {
		return deals.get(position).getId();
	}
	
	public int getItemSize() {
		return deals.size();
	}
}
